﻿using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Learun.Util.SqlSugar;
using Pipelines.Sockets.Unofficial.Arenas;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;

namespace Learun.Application.Web.AppApi
{
    /// <summary>
    /// 对象类型接口
    /// </summary>
    [RoutePrefix("api/ObjectTypeApi")]
    [HandlerApiLogin(FilterMode.Enforce)]
    [TokenAuthorize]
    public class ObjectTypeApiController : WebApiControllerBase
    {
        private ec_objecttypeIBLL ec_objecttypeIBLL = new ec_objecttypeBLL();
        private ec_objecttypepIBLL ec_objecttypepIBLL = new ec_objecttypepBLL();
        private ec_enginedataIBLL ec_enginedataIBLL = new ec_enginedataBLL();
        private ec_enginedata_pixelIBLL ec_enginedata_pixelIBLL = new ec_enginedata_pixelBLL();
        private ec_enginedata_propertyIBLL ec_enginedata_propertyIBLL = new ec_enginedata_propertyBLL();

        /// <summary>
        /// 获取对象类型。根据datatype，有3种方式。返回TreeModel。
        /// 插件端里的设计浏览会用
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="dataType">节点类型 0:对象类型、1:位号、2:图纸</param>
        /// <param name="KeyWord">关键字</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(List<TreeModel>))]
        public IHttpActionResult GetObjectTypeData(string projectId, string dataType, string KeyWord = "")
        {
            try
            {
                var treeList = ec_objecttypeIBLL.GetObjectTypeData3Level(projectId, dataType, KeyWord);
                return Success(treeList);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }


        /// <summary>
        /// 获取某一个对象类型的属性信息。包含详细的内容，比如属性的类型（字符串、数字、枚举等）
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="objectTypeID">对象类型ID</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(ec_objecttypepEntity))]
        public IHttpActionResult GetObjectTypePById(string projectId, string objectTypeID)
        {
            try
            {
                var data = ec_objecttypepIBLL.GetObjectTypePById(objectTypeID, projectId, true);
                return Success(data);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取一组对象类型的属性信息。为<see cref="GetObjectTypePById(string, string)"/>的批量版本
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="objectTypeIDs">对象类型ID集合（用,连接）</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetObjectTypePListByIds(string projectId, string objectTypeIDs)
        {
            try
            {
                var data = ec_objecttypepIBLL.GetObjectTypePById(objectTypeIDs, projectId, true);
                return Success(data);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 二期：获取对象类型的命名规则的信息。projectId为0时，认为是查询公司级
        /// </summary>
        /// <param name="projectId">项目ID。projectId为0时，认为是查询公司级</param>
        /// <param name="objectTypeID">对象类型ID</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(ec_objecttypenamingconvEntity))]
        public IHttpActionResult GetObjectTypeNamingConv(string projectId, string objectTypeID)
        {
            try
            {
                if (projectId == "0")
                {
                    var data = new ec_objecttypenamingconvBLL().GetList("{\"ObjectTypeID\":\"" + objectTypeID + "\"}").ToList();
                    return Success(data);
                }
                else
                {
                    var data = new ec_objecttypenamingconvBLL().GetList("{\"ProjectId\":\"" + projectId + "\",\"ObjectTypeID\":\"" + objectTypeID + "\"}").ToList();
                    return Success(data);
                }

            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }



        /// <summary>
        /// 获取对象类型下的所有现有位号清单
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="objectTypeID">对象类型ID</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(ec_enginedataEntity))]
        public IHttpActionResult GetTagNumberById(string projectId, string objectTypeID)
        {
            try
            {
                var data = ec_enginedataIBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"ObjectTypeID\":\"" + objectTypeID + "\"}").ToList();
                return Success(data);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
        /// <summary>
        /// 获取对象类型下的所有现有位号清单（仅有位号）。
        /// <see cref="GetTagNumberById(string, string)"/>的精简版本。
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="objectTypeID">对象类型ID</param>
        /// <param name="KeyWord">关键字</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(TreeModelLite))]
        public IHttpActionResult GetTagNumberById_Brief(string projectId, string objectTypeID, string KeyWord = "", string system = "")
        {
            try
            {
                List<TreeModelLite> res = new List<TreeModelLite>();
                system = WebHelper.UrlDecode(system);
                List<ec_enginedataEntity> data = new List<ec_enginedataEntity>();
                
                    data = ec_enginedataIBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"system\":\"" + system + "\",\"ObjectTypeID\":\"" + objectTypeID + "\",\"TagNumberFilter\":\"" + KeyWord + "\"}").ToList();
 
                foreach (var tag in data)
                {
                    res.Add(new TreeModelLite() { id = tag.EngineDataID, text = tag.TagNumber });
                }
                return Success(res);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取某一个对象类型的元件库数据
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="objectTypeID">对象类型ID</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(ec_library_fileEntity))]
        public IHttpActionResult GetLibraryDataById(string projectId, string objectTypeID)
        {
            try
            {
                var data = new ec_library_fileBLL().GetList("{\"ProjectId\":\"" + projectId + "\",\"ObjectTypeID\":\"" + objectTypeID + "\"}").ToList();
                return Success(data);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取位号的工程属性（根据位号）
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="tagNumber">位号</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(ec_enginedataEntity))]
        public IHttpActionResult GetEngineDataByTag(string projectId, string tagNumber, string caseId = "")
        {
            try
            {
                var data = ec_enginedataIBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"TagNumber\":\"" + tagNumber + "\"}").ToList();
                if (data != null && data.Count > 0)
                {
                    //获取工程数据属性
                    data[0].EngineDataProperty = ec_enginedata_propertyIBLL.GetEnginePropById(projectId, data[0].EngineDataID, caseId).ToList();
                }
                return Success(data);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取位号的工程属性（根据一堆位号）
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="tagNumber">位号集合（用,连接）</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetEngineDataListByTags(string projectId, string tagNumber)
        {
            try
            {
                var data = ec_enginedataIBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"TagNumbers\":\"" + tagNumber + "\"}").ToList();
                if (data != null && data.Count > 0)
                {
                    List<string> engineDataIDList = data.Select(x => x.EngineDataID).ToList();
                    string engineDataIDs = string.Join(",", (from tb in engineDataIDList select tb).ToList());
                    var AllEngineDataProperty = new ec_enginedata_propertyBLL().GetEnginePropById(projectId, engineDataIDs).ToList();
                    foreach (var item in data)
                    {
                        //获取工程数据属性
                        item.EngineDataProperty = AllEngineDataProperty.FindAll(x => x.EngineDataID == item.EngineDataID).ToList();
                    }
                }
                return Success(data);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取图纸工程数据（以图纸为基础）
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingCatalogueID">图纸目录ID</param>
        /// <param name="drawingFileID">图纸文件ID。为0时，相当于全局</param>
        /// <param name="objectTypeID">对象类型ID</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(ec_enginedata_pixelEntity))]
        public IHttpActionResult GetDrawingEngineData(string projectId, string drawingCatalogueID, string drawingFileID = "", string objectTypeID = "")
        {
            try
            {
                var listEnginePixel = ec_enginedata_pixelIBLL.GetDrawingEnginePixel("{\"ProjectId\":\"" + projectId + "\",\"DrawingCatalogueID\":\"" + drawingCatalogueID + "\",\"DrawingFileID\":\"" + drawingFileID + "\",\"ObjectTypeID\":\"" + objectTypeID + "\"}").ToList();
                if (listEnginePixel != null && listEnginePixel.Count > 0)
                {
                    List<string> listEngineDataID = listEnginePixel.Select(x => x.EngineDataID).Distinct().ToList();
                    //获取对应的属性
                    List<ec_enginedata_propertyEntity> listEngineProp = ec_enginedata_propertyIBLL.GetEnginePropByList(projectId, listEngineDataID).ToList();
                    //获取对应的属性组、属性
                    List<string> listObjectTypeID = listEnginePixel.Select(x => x.ObjectTypeID).Distinct().ToList();
                    string strObjectTypeID = string.Join(",", (from tb in listObjectTypeID select tb).ToList());
                    List<ec_objecttypepEntity> listObjectYypeP = ec_objecttypepIBLL.GetObjectTypePById(strObjectTypeID, projectId, true).ToList();
                    foreach (var item in listEnginePixel)
                    {
                        item.EngineDataProperty = new List<ec_enginedata_propertyEntity>();
                        //根据工程数据对应的属性数据
                        var listEnginePropById = listEngineProp.FindAll(x => x.EngineDataID == item.EngineDataID);
                        //获取当前图元对应的对象类型属性
                        var curObjectTypeP = listObjectYypeP.FindAll(x => x.ObjectTypeID == item.ObjectTypeID);
                        foreach (var objectType in curObjectTypeP)
                        {
                            //根据属性名在工程数据表里面找到对应的属性值
                            var curEngineProp = listEnginePropById.Find(x => x.PropertyName == objectType.PropertyName);
                            //属性值不为空才返回
                            if (!string.IsNullOrEmpty(curEngineProp?.PropertyValue))
                            {
                                ec_enginedata_propertyEntity model = new ec_enginedata_propertyEntity();
                                model.EngineDataPropertyID = curEngineProp.EngineDataPropertyID;
                                model.EngineDataID = curEngineProp.EngineDataID;
                                model.PropertyGroupName = objectType.PropertyGroupName;
                                model.PropertyName = curEngineProp.PropertyName;
                                model.PropertyNameEN = objectType.PropertyNameEN;
                                model.PropertyValue = curEngineProp.PropertyValue;
                                item.EngineDataProperty.Add(model);
                            }
                        }
                    }
                }
                return Success(listEnginePixel);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 判断位号是否重复，如果返回实体(前端再会根据objecttype类型做进一步判断)，如果返回null则不重复
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="oldTagNumber">修改前位号</param>
        /// <param name="newTagNumber">修改后位号</param>
        /// <returns></returns>
        [ResponseType(typeof(Boolean))]
        [HttpGet]
        public IHttpActionResult IsRepeatByTagNumber(string projectId, string oldTagNumber, string newTagNumber)
        {
            try
            {
                if (oldTagNumber != newTagNumber)
                {
                    var data = ec_enginedataIBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"TagNumber\":\"" + newTagNumber + "\"}").ToList();
                    if (data != null && data.Count > 0)
                    {
                        return Success(data[0]);
                    }
                }
                return Success(null);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 对象浏览器修改位号
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="oldTagNumber">修改前位号</param>
        /// <param name="newTagNumber">修改后位号</param>
        /// <param name="isCover">是否覆盖:覆盖 1，不覆盖 0</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult UpdateTagNumber(string projectId, string oldTagNumber, string newTagNumber, string isCover)
        {
            try
            {
                ec_enginedataIBLL.RenameTagNumber(projectId, oldTagNumber, newTagNumber, isCover);
                return Success("保存成功！");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 根据图元编号(CAD里的句柄）获取位号
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param>
        /// <param name="pixelCode">图元编号</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetTagNumberByPixel(string projectId, string drawingFileID, string pixelCode)
        {
            try
            {
                var engineData = ec_enginedataIBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"DrawingFileID\":\"" + drawingFileID + "\",\"PixelCode\":\"" + pixelCode + "\"}");
                return Success(engineData.FirstOrDefault());
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }



        /// <summary>
        /// 新做的根据CAD里的句柄获取位号的全部信息（By Yuxingheng）
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param>
        /// <param name="pixelCodes">图元编号集合（用,连接）</param>
        /// <param name="caseID">工况ID</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetTagInfosByPixels(string projectId, string drawingFileID, string pixelCodes, string caseID = "")
        {
            //新版本
            {
                var relBll = new ec_enginedata_relBLL();
                var ec_enginedata_pixelIBLL = new ec_enginedata_pixelBLL();
                var stopWatch = new Stopwatch();
                var actionDescriptor = this.ActionContext.ActionDescriptor;
                var actionName = actionDescriptor.ActionName;
                var controllerName = actionDescriptor.ControllerDescriptor.ControllerName;

                if (pixelCodes == "")
                {
                    return null;
                }
                //查询所有的位号基础信息
                stopWatch.Start();
                var engineData = ec_enginedataIBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"DrawingFileID\":\"" + drawingFileID + "\",\"PixelCodes\":\"" + pixelCodes + "\"}").ToList();
                stopWatch.Stop();
                this.Logger.Info(DateTime.Now.ToString() + ", " + controllerName + "-" + actionName + "图纸ID：" + drawingFileID + ",新版查询所有的位号基础信息运行时长:" + stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + "\r\n");
                #region OPC
                var opcBll = new ec_OPCBLL();
                var allOPCs = opcBll.GetList2EngineData(projectId, "", "");
                var OPCs = opcBll.GetList2EngineData(projectId, drawingFileID, pixelCodes);
                engineData.AddRange(OPCs); //opc额外处理
                var OPCProps = opcBll.GetProps2EngineProp(projectId);
                #endregion

                //得到所有的类别(不重复的）
                stopWatch.Start();
                var objectTypes = engineData.Select(x => x.ObjectTypeID).Distinct().ToList();

                string objectTypeIDs = "";
                var ec_objecttypeBLL = new ec_objecttypeBLL();
                var resultCol = new List<ec_objecttypeEntity>();
                foreach (var objectType in objectTypes)//可能有opc，可能没有opc，看OPCs的结果
                {
                    //resultCol.Add(ec_objecttypeBLL.GetEntity(objectType, projectId));
                    objectTypeIDs += objectType + ",";
                }


                resultCol = ec_objecttypeBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"ObjectTypeIDs\":\"" + objectTypeIDs + "\"}",
                     null, true).ToList();//会额外处理opc
                if (objectTypeIDs != "")
                {
                    objectTypeIDs = objectTypeIDs.Substring(0, objectTypeIDs.Length - 1);
                }
                else
                {
                    return Ok(resultCol);
                }
                stopWatch.Stop();
                this.Logger.Info(DateTime.Now.ToString() + ", " + controllerName + "-" + actionName + " 新版得到所有的类别(不重复的）运行时长:" + stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + "\r\n");
                stopWatch.Start();
                //所有类别的属性信息
                //stopWatch.Start();
                var objectTypeProps = new ec_objecttypepBLL().GetObjectTypePById(objectTypeIDs, projectId, true);//opc额外处理
                //stopWatch.Stop();
                //this.Logger.Info(DateTime.Now.ToString() + ", " + controllerName + "-" + actionName + " 新版所有类别的属性信息运行时长:" + stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + "\r\n");

                var ec_enginedata_propertyBLL = new ec_enginedata_propertyBLL();
                //GetProjectCodeList
                stopWatch.Stop();
                this.Logger.Info(DateTime.Now.ToString() + ", " + controllerName + "-" + actionName + " 新版得到所有类别的属性信息:" + stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + "\r\n");

                //GetEngineDataListByTags
                stopWatch.Start();
                var listEngineDataID = engineData.Select(x => x.EngineDataID).Distinct().ToList();
                //一次查询全部属性信息（不包含opc的）
                var engineDataProps = ec_enginedata_propertyBLL.GetEnginePropByList(projectId, listEngineDataID, caseID);
                //一次查询全部的位号信息（同样不包含opc的）
                var allTags = ec_enginedataIBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"ObjectTypeIDs\":\"" + objectTypeIDs + "\"}").ToList();
                stopWatch.Stop();
                this.Logger.Info(DateTime.Now.ToString() + ", " + controllerName + "-" + actionName + " 新版一次查询全部属性信息运行时长:" + stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + "\r\n");
                stopWatch.Start();

                //一次查询图上的所有句柄
                var allPixels = ec_enginedata_pixelIBLL.GetDrawingEnginePixel("{\"ProjectId\":\"" + projectId + "\",\"DrawingFileID\":\"" + drawingFileID + "\"}").ToList();

                //clear
                //stopWatch.Stop();
                //ec_enginedata_pixelIBLL.Clear(drawingFileID, projectId);
                //this.Logger.Info(DateTime.Now.ToString() + ", " + controllerName + "-" + actionName + " 新版clear无效的图元信息:" + stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + "\r\n");
                //stopWatch.Start();


                foreach (var objectType in resultCol)
                {
                    //该类型下的属性信息
                    objectType.props = objectTypeProps.Where(x => x.ObjectTypeID == objectType.ObjectTypeID).ToList();
                    //该类型下的位号基础信息
                    objectType.tags = engineData.Where(x => x.ObjectTypeID == objectType.ObjectTypeID).ToList();
                    foreach (var tag in objectType.tags)
                    {
                        //电缆from to
                        var CableConn = relBll.GetCableConn(tag.EngineDataID, projectId);

                        //每个位号的属性信息
                        if (objectType.ObjectTypeID == "OPC")
                        {
                            tag.EngineDataProperty = OPCProps.Where(x => x.EngineDataID == tag.EngineDataID).ToList();
                        }
                        else
                        {
                            tag.EngineDataProperty = engineDataProps.Where(x => x.EngineDataID == tag.EngineDataID).ToList();
                            //BUG 1483
                            if (!tag.EngineDataProperty.Any(X => X.PropertyName == "起始设备"))
                            {
                                var newProp = new ec_enginedata_propertyEntity()
                                {
                                    EngineDataID = tag.EngineDataID,
                                    PropertyName = "起始设备",
                                    CaseID = string.IsNullOrEmpty(caseID) ? tag.CaseID : caseID,
                                };
                                newProp.Create();

                                ec_enginedata_propertyBLL.InsertTagProp(projectId, tag.EngineDataID, newProp);
                                tag.EngineDataProperty.Add(newProp);
                            }
                            if (!tag.EngineDataProperty.Any(X => X.PropertyName == "终止设备"))
                            {
                                var newProp = new ec_enginedata_propertyEntity()
                                {
                                    EngineDataID = tag.EngineDataID,
                                    PropertyName = "终止设备",
                                    CaseID = string.IsNullOrEmpty(caseID) ? tag.CaseID : caseID,
                                };
                                newProp.Create();

                                ec_enginedata_propertyBLL.InsertTagProp(projectId, tag.EngineDataID, newProp);
                                tag.EngineDataProperty.Add(newProp);
                            }

                            foreach (ec_enginedata_propertyEntity TagProp in tag.EngineDataProperty)
                            {
                                if (TagProp.PropertyName == "起始设备")
                                {
                                    TagProp.PropertyValue = CableConn.End1Tag;
                                }
                                else if (TagProp.PropertyName == "终止设备")
                                {
                                    TagProp.PropertyValue = CableConn.End2Tag;
                                }
                            }
                        }

                        //查一下每个位号的图元信息
                        tag.EngineDataPixel = allPixels.Where(x => x.EngineDataID == tag.EngineDataID).ToList();
                    }
                    //该类型下的位号下拉清单
                    if (objectType.ObjectTypeID == "OPC")
                    {
                        objectType.tagsListDropDown = allOPCs.ToDictionary(X => X.EngineDataID, X => X.TagNumber);
                        objectType.IsSerialNumber = 1;
                        objectType.TagAutoBySerialNumber = "OPC" + (1 + allOPCs.Count()).ToString();
                    }
                    else
                    {
                        objectType.tagsListDropDown = allTags.ToDictionary(x => x.EngineDataID, x => x.TagNumber);

                        //该类型下的流水
                        if (objectType.IsSerialNumber == 1)
                        {
                            int SerialNumber = 1;
                            if (engineData != null && allTags.Count > 0)
                            {
                                SerialNumber = engineData.Max(x => x.SerialNumber).ToInt() + 1;
                            }
                            objectType.TagAutoBySerialNumber = objectType.ObjectTypeNameEN + SerialNumber;
                        }
                    }

                }
                stopWatch.Stop();
                this.Logger.Info(DateTime.Now.ToString() + ", " + controllerName + "-" + actionName + " 新版GetEngineDataListByTags运行时长:" + stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + "\r\n");
                return Ok(resultCol);
                //this.Logger.Info(DateTime.Now.ToString() + ", " + controllerName + "-" + actionName + " 新版返回resultCol结果:" + JsonConvert.SerializeObject(resultCol) + "\r\n");
            }



            //未改动
            {
                var stopWatch = new Stopwatch();
                var actionDescriptor = this.ActionContext.ActionDescriptor;
                var actionName = actionDescriptor.ActionName;
                var controllerName = actionDescriptor.ControllerDescriptor.ControllerName;

                if (pixelCodes == "")
                {
                    return null;
                }
                //查询所有的位号基础信息

                stopWatch.Start();
                var engineData = ec_enginedataIBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"DrawingFileID\":\"" + drawingFileID + "\",\"PixelCodes\":\"" + pixelCodes + "\"}");
                stopWatch.Stop();
                this.Logger.Info(DateTime.Now.ToString() + ", " + controllerName + "-" + actionName + " 查询所有的位号基础信息运行时长:" + stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + "\r\n");


                //得到所有的类别(不重复的）
                stopWatch.Start();
                var objectTypes = engineData.Select(x => x.ObjectTypeID).Distinct();

                string objectTypeIDs = "";
                var ec_objecttypeBLL = new ec_objecttypeBLL();
                var resultCol = new List<ec_objecttypeEntity>();
                foreach (var objectType in objectTypes)
                {
                    resultCol.Add(ec_objecttypeBLL.GetEntity(objectType, projectId));
                    objectTypeIDs += objectType + ",";
                }
                if (objectTypeIDs != "")
                {
                    objectTypeIDs = objectTypeIDs.Substring(0, objectTypeIDs.Length - 1);
                }
                stopWatch.Stop();
                this.Logger.Info(DateTime.Now.ToString() + ", " + controllerName + "-" + actionName + " 得到所有的类别(不重复的）运行时长:" + stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + "\r\n");

                //所有类别的属性信息
                var objectTypeProps = new ec_objecttypepBLL().GetObjectTypePById(objectTypeIDs, projectId, true);
                var ec_enginedata_propertyBLL = new ec_enginedata_propertyBLL();
                //GetProjectCodeList

                //GetEngineDataListByTags
                stopWatch.Start();
                foreach (var objectType in resultCol)
                {
                    //该类型下的属性信息
                    objectType.props = objectTypeProps.Where(x => x.ObjectTypeID == objectType.ObjectTypeID).ToList();
                    //该类型下的位号基础信息
                    objectType.tags = engineData.Where(x => x.ObjectTypeID == objectType.ObjectTypeID).ToList();
                    foreach (var tag in objectType.tags)
                    {
                        //每个位号的属性信息
                        tag.EngineDataProperty = ec_enginedata_propertyBLL.GetEnginePropById(projectId, tag.EngineDataID).ToList();

                    }
                    //该类型下的位号下拉清单
                    var allTags = ec_enginedataIBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"ObjectTypeID\":\"" + objectType.ObjectTypeID + "\"}").ToList();
                    objectType.tagsListDropDown = allTags.ToDictionary(x => x.EngineDataID, x => x.TagNumber);

                    //该类型下的流水
                    if (objectType.IsSerialNumber == 1)
                    {
                        int SerialNumber = 1;
                        if (engineData != null && allTags.Count > 0)
                        {
                            SerialNumber = engineData.Max(x => x.SerialNumber).ToInt() + 1;
                        }
                        objectType.TagAutoBySerialNumber = objectType.ObjectTypeNameEN + SerialNumber;
                    }
                }
                stopWatch.Stop();
                this.Logger.Info(DateTime.Now.ToString() + ", " + controllerName + "-" + actionName + " GetEngineDataListByTags运行时长:" + stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + "\r\n");
                //this.Logger.Info(DateTime.Now.ToString() + ", " + controllerName + "-" + actionName + " 返回resultCol结果:" + JsonConvert.SerializeObject(resultCol) + "\r\n");
                return Ok(resultCol);
            }
        }
        /// <summary>
        /// 新做的根据位号获取位号的全部信息（By Yuxingheng）
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="Tags">Tag Number的集合（用,连接）</param> 
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetTagInfosByTags(string projectId, string Tags, string caseID = "")
        {
            if (Tags == "")
            {
                return null;
            }
            //查询所有的位号基础信息
            var engineData = ec_enginedataIBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"TagNumbers\":\"" + Tags + "\"}");
            //得到所有的类别(不重复的）
            var objectTypes = engineData.Select(x => x.ObjectTypeID).Distinct();

            string objectTypeIDs = "";
            var relBll = new ec_enginedata_relBLL();
            var resultCol = new List<ec_objecttypeEntity>();
            foreach (var objectTypeId in objectTypes)
            {
                resultCol.Add(ec_objecttypeIBLL.GetEntity(objectTypeId, projectId));
                objectTypeIDs += objectTypeId + ",";
            }
            if (objectTypeIDs != "")
            {
                objectTypeIDs = objectTypeIDs.Substring(0, objectTypeIDs.Length - 1);
            }
            else
            {
                return Ok(resultCol);
            }
            //一次查询全部属性信息
            var listEngineDataID = engineData.Select(x => x.EngineDataID).Distinct().ToList();
            var engineDataProps = ec_enginedata_propertyIBLL.GetEnginePropByList(projectId, listEngineDataID, caseID);
            //所有类别的属性信息
            var objectTypeProps = ec_objecttypepIBLL.GetObjectTypePById(objectTypeIDs, projectId, true);
            //所有类别的已有位号清单
            var allTags = ec_enginedataIBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"ObjectTypeIDs\":\"" + objectTypeIDs + "\"}").ToList();

            //GetProjectCodeList

            //GetEngineDataListByTags
            foreach (var objectType in resultCol)
            {
                //该类型下的属性信息
                objectType.props = objectTypeProps.Where(x => x.ObjectTypeID == objectType.ObjectTypeID).ToList();
                //该类型下的位号基础信息
                objectType.tags = engineData.Where(x => x.ObjectTypeID == objectType.ObjectTypeID).ToList();
                //foreach (var tag in objectType.tags)
                //{
                //    //每个位号的属性信息
                //    tag.EngineDataProperty = ec_enginedata_propertyBLL.GetEnginePropById(projectId, tag.EngineDataID).ToList();

                //}
                foreach (var tag in objectType.tags)
                {
                    //电缆from to
                    var CableConn = relBll.GetCableConn(tag.EngineDataID, projectId);

                    //每个位号的属性信息
                    //tag.EngineDataProperty = ec_enginedata_propertyBLL.GetEnginePropById(projectId, tag.EngineDataID).ToList();
                    tag.EngineDataProperty = engineDataProps.Where(x => x.EngineDataID == tag.EngineDataID).ToList();

                    //BUG 1483
                    if (!tag.EngineDataProperty.Any(X => X.PropertyName == "起始设备"))
                    {
                        var newProp = new ec_enginedata_propertyEntity()
                        {
                            EngineDataID = tag.EngineDataID,
                            PropertyName = "起始设备",
                            CaseID = string.IsNullOrEmpty(caseID) ? tag.CaseID : caseID,
                        };
                        newProp.Create();

                        ec_enginedata_propertyIBLL.InsertTagProp(projectId, tag.EngineDataID, newProp);
                        tag.EngineDataProperty.Add(newProp);
                    }
                    if (!tag.EngineDataProperty.Any(X => X.PropertyName == "终止设备"))
                    {
                        var newProp = new ec_enginedata_propertyEntity()
                        {
                            EngineDataID = tag.EngineDataID,
                            PropertyName = "终止设备",
                            CaseID = string.IsNullOrEmpty(caseID) ? tag.CaseID : caseID,
                        };
                        newProp.Create();

                        ec_enginedata_propertyIBLL.InsertTagProp(projectId, tag.EngineDataID, newProp);
                        tag.EngineDataProperty.Add(newProp);
                    }

                    foreach (ec_enginedata_propertyEntity TagProp in tag.EngineDataProperty)
                    {
                        if (TagProp.PropertyName == "起始设备")
                        {
                            TagProp.PropertyValue = CableConn.End1Tag;
                        }
                        else if (TagProp.PropertyName == "终止设备")
                        {
                            TagProp.PropertyValue = CableConn.End2Tag;
                        }
                    }
                    //查一下每个位号的图元信息
                    tag.EngineDataPixel = ec_enginedata_pixelIBLL.GetEnginePixelById(projectId, tag.EngineDataID).ToList();
                }
                //该类型下的位号下拉清单 
                objectType.tagsListDropDown = allTags.ToDictionary(x => x.EngineDataID, x => x.TagNumber);

                //该类型下的流水
                if (objectType.IsSerialNumber == 1)
                {
                    int SerialNumber = 1;
                    if (engineData != null && allTags.Count > 0)
                    {
                        SerialNumber = engineData.Max(x => x.SerialNumber).ToInt() + 1;
                    }
                    objectType.TagAutoBySerialNumber = objectType.ObjectTypeNameEN + SerialNumber;
                }
            }
            return Ok(resultCol);
        }
        /// <summary>
        /// 根据一组图元编号获取一组位号
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param>
        /// <param name="pixelCodes">图元编号集合（用,连接）</param>
        /// <param name="Distinct">是否返回一一对应</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetTagNumberListByPixels(string projectId, string drawingFileID, string pixelCodes, bool Distinct = true)
        {
            try
            {
                var engineData = ec_enginedataIBLL.GetListByPixel(projectId, drawingFileID, pixelCodes);
                return Success(engineData);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 图元属性修改
        /// </summary>
        /// <param name="projectId">项目ID</param> 
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult UpdatePixelAndProp(string projectId)
        {
            try
            {
                var asyncContent = Request.Content.ReadAsStringAsync().Result;
                ec_enginedataEntity entity = asyncContent.ToObject<ec_enginedataEntity>();
                ec_enginedataIBLL.UpdatePixelAndProp(projectId, entity);
                return Success("保存成功！");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
        /// <summary>
        /// 用于DuplicatePixelBatch接口的数据体
        /// </summary>
        public class DuplicatePixelType
        {
            /// <summary>
            /// 新图例句柄
            /// </summary>
            public string newPixelCode { get; set; }
            /// <summary>
            /// 原本的图例句柄
            /// </summary>
            public string oldPixelCode { set; get; }
        }
        /// <summary>
        /// 图例复制接口，让新图例也能和旧的位号关联（By YUXH)
        /// </summary>
        /// <param name="ProjectId">项目ID</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult DuplicatePixelBatch(string ProjectId, string newDrawingID, string oldDrawingID, [FromBody] List<DuplicatePixelType> data)
        {
            try
            {
                //serv
                var pixelServ = new ec_enginedata_pixelService();

                var stopWatch = new Stopwatch();
                stopWatch.Start();

                var ProjectEntity = new ec_projectService().GetEntity(ProjectId);
                if (ProjectEntity == null)
                {
                    return Fail($"无效的ProjectID。"); ;
                }

                foreach (var DuplicatePixelData in data)
                {
                    //先根据老的图例，找出工程ID 
                    var EngineDataIDs = pixelServ.GetList("{\"ProjectId\":\"" + ProjectId + "\",\"PixelCode\":\"" + DuplicatePixelData.oldPixelCode + "\",\"DrawingFileID\":\"" + oldDrawingID + "\"}").
                                                            Where(x => x.EngineDataID != "").
                                                            Select(x => x.EngineDataID).Distinct();
                    if (EngineDataIDs != null && EngineDataIDs.Count() == 1)
                    {
                        var EngineDataID = EngineDataIDs.First();
                        //查一下原来有没有
                        var sql = "";
                        sql = $@"select * from ec_enginedata_pixel_{ProjectEntity.ProjectIndex} t1 where t1.DrawingFileID='{newDrawingID}' and t1.PixelCode='{DuplicatePixelData.newPixelCode}' and t1.EngineDataID='{EngineDataID}'";

                        var existObj = SqlSugarHelper.Db.Ado.SqlQuerySingle<ec_enginedata_pixelEntity>(sql);

                        if (existObj == null)
                        {
                            var pixelCol = new ec_enginedata_pixelEntity()
                            {
                                EngineDataPixelID = "",
                                EngineDataID = EngineDataID,
                                DrawingFileID = newDrawingID,
                                PixelCode = DuplicatePixelData.newPixelCode
                            };
                            pixelServ.SavePixelBatch(EngineDataID, pixelCol, ProjectId);
                        }




                    }
                    else
                    {
                        return Fail($"根据句柄{DuplicatePixelData.oldPixelCode}查询出有多个记录。");
                    }
                }



                stopWatch.Stop();
                var actionDescriptor = this.ActionContext.ActionDescriptor;
                var actionName = actionDescriptor.ActionName;
                var controllerName = actionDescriptor.ControllerDescriptor.ControllerName;
                this.Logger.Info(DateTime.Now.ToString() + ", " + controllerName + "-" + actionName + " 运行时长:" + stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + "\r\n");

                return Success("保存成功！");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 图元属性批量修改（By Xingheng.Yu）
        /// </summary>
        /// <param name="projectId">项目ID</param> 
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult UpdatePixelAndPropBatch(string projectId)
        {
            try
            {
                var stopWatch = new Stopwatch();
                stopWatch.Start();
                var asyncContent = Request.Content.ReadAsStringAsync().Result;
                List<ec_enginedataEntity> entitys = asyncContent.ToObject<List<ec_enginedataEntity>>();
                foreach (var tag in entitys)
                {
                    if (!string.IsNullOrEmpty(tag.TagNumber))
                    {
                        ec_enginedataIBLL.UpdatePixelAndProp(projectId, tag);
                    }

                }
                stopWatch.Stop();
                var actionDescriptor = this.ActionContext.ActionDescriptor;
                var actionName = actionDescriptor.ActionName;
                var controllerName = actionDescriptor.ControllerDescriptor.ControllerName;
                this.Logger.Info(DateTime.Now.ToString() + ", " + controllerName + "-" + actionName + " 运行时长:" + stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture) + "\r\n");

                return Success("保存成功！");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
        /// <summary>
        /// 获取最新流水号
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="objectTypeID">对象类型ID</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetLatestSerialNumber(string projectId, string objectTypeID)
        {
            try
            {
                var objecttype = ec_objecttypeIBLL.GetEntity(objectTypeID, projectId);
                //判断是否需要生成流水号
                if (objecttype?.IsSerialNumber == 1)
                {
                    int SerialNumber = 1;
                    var engineData = ec_enginedataIBLL.GetList("{\"ProjectId\":\"" + projectId + "\",\"ObjectTypeID\":\"" + objectTypeID + "\"}").ToList();
                    if (engineData != null && engineData.Count > 0)
                    {
                        SerialNumber = engineData.Max(x => x.SerialNumber).ToInt() + 1;
                    }
                    return SuccessString(objecttype?.ObjectTypeNameEN + SerialNumber);
                }
                else
                {
                    return SuccessString("");
                }
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 通用的拿工程数据的方法.（BY YuXH）
        /// 
        /// </summary>
        /// <param name="sqlWhere">直接where的字符串，而不是json。比如PropertyName='xxx' and PropertyValue='yyy'。如果要以某些通用的属性查询，如createuserid，要加表前缀。如t1.createuserid</param>
        /// <param name="projId">0时，无效</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(ec_enginedataEntity))]
        public IHttpActionResult GetListBySQL(string sqlWhere, string projId)
        {
            var engineData = ec_enginedataIBLL.GetListBySQL(sqlWhere, projId).ToList();
            return Success(engineData);
        }

        /// <summary>
        /// 获取某个位号的某个属性的历史数据
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="tagNumber">位号</param>
        /// <param name="propertyName">属性名称</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(ec_enginedata_propertyhisEntity))]
        public IHttpActionResult GetHistoryData(string projectId, string tagNumber, string propertyName)
        {
            try
            {
                var data = new ec_enginedata_propertyhisBLL().GetList("{\"ProjectId\":\"" + projectId + "\",\"TagNumber\":\"" + tagNumber + "\",\"PropertyName\":\"" + propertyName + "\"}");
                return Success(data);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }



    }
}